//
//  LoginViewController.m
//  WGFGlobalHouse
//
//  Created by waiguofang on 15/4/14.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//  登录

#import "LoginViewController.h"
#import "MainViewController.h"
#import "BindingPhoneViewController.h"
#import "SingletonData.h"
#import "AppDelegate.h"
#import "WGFHttpTool.h"
#import "GetBackPwdViewController.h"
#import "BrokerRegisterVC.h"
#import "BaseNvc.h"
#import "LoginDataMange.h"
#import "UserModal.h"
#import "SingletonData.h"
#import "CheckNetWorkTool.h"
#import "MBProgressHUD+MJ.h"
#import "UIView+circular.h"

#import "StringTool.h"
#import "TabBarVC.h"

#import "MainViewController.h"
#import "IWNavigationController.h"

#import "MyXMPP.h"



@interface LoginViewController ()<UITextFieldDelegate>
- (IBAction)login;
- (IBAction)getBackPwd;
- (IBAction)clickToBeMiddleManBtn;


//用户名
@property (weak, nonatomic) IBOutlet UITextField *userName;
//密码
@property (weak, nonatomic) IBOutlet UITextField *pwd;

@property (weak, nonatomic) IBOutlet UIView *backView;
@property (copy, nonatomic) NSString *str;
@property (strong, nonatomic) LoginDataMange *dataMange;
@property (strong, nonatomic) UserModal *model;
@property(nonatomic,assign) BOOL isExit;

@property (nonatomic,assign)CGFloat keyboardHeight;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end


@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //监听键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name: UIKeyboardWillHideNotification object:nil];
    
    self.dataMange = [[LoginDataMange alloc]init];
   
    [self readLoginInfo];
   
    [self addLeftViewToTextFiled];
    
    
   
    
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.view endEditing:YES];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
     self.navigationController.navigationBarHidden = YES;
}
/**
 *  给输入框 添加图片
 */
-(void)addLeftViewToTextFiled
{
    
    
    UIImageView *firstImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
    [firstImg setImage:[UIImage imageNamed:@"login_username_icon"]];
    
    UIView *firstView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 20)];
    [firstView addSubview:firstImg];
    self.userName.leftView = firstView;
    self.userName.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView *secondImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
    [secondImg setImage:[UIImage imageNamed:@"login_password_icon"]];
    UIView *secondView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 20)];
    [secondView addSubview:secondImg];
    self.pwd.leftView = secondView;
    self.pwd.leftViewMode = UITextFieldViewModeAlways;
    
    
    [self.userName setTextAlignment:NSTextAlignmentJustified];
    
    [self.loginBtn viewToCircular];
    
}


/**
 *  登录
 */
- (IBAction)login
{
    [self.view endEditing:YES];
    if ([self checkUsernameAndPwd]) {
       
        [self checkUseInfo];
    }
}

#pragma mark 校验登陆信息
-(BOOL)checkUsernameAndPwd
{
    if ([StringTool isBlankString:self.userName.text]) {
        [MBProgressHUD showError:@"请输入用户名"];
        return NO;
    }else if ([StringTool isBlankString:self.pwd.text])
    {
        [MBProgressHUD showError:@"请输入密码"];
        return NO;
    }
    return YES;
}

#pragma mark 发送请求（发送用户名和密码）
-(void)checkUseInfo
{
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
      __weak typeof(self) bself = self;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        ResulteMod *resuleMod = [bself.dataMange loginWithAccount:bself.userName.text WithPassword:bself.pwd.text];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            if (resuleMod.resltState==ResultSuccess) {//成功  20003
                
                bself.model = [[UserModal alloc]initWithDic:resuleMod.dataMod];
                bself.model.keyboardHeight = 250;
                
                [bself saveLoginInfo];
                
                [[MyXMPP sharedMyXMPP] connect];
                
                //第一次登录,去激活账号
                if ([bself isToBingVc])
                {
                    BindingPhoneViewController *vc = [[BindingPhoneViewController alloc]initWithNibName:@"BindingPhoneViewController" bundle:nil];
                    [bself.navigationController pushViewController:vc animated:YES];
                }
                else
                {
                    
                    if (bself.model.userType == UserTypeCustomer) {
                        
                       
                        AppDelegate *app = [AppDelegate sharedAppDelegate];
                        MainViewController *mainVC = [[MainViewController alloc]init];
                        
                        
                        UINavigationController *navigationVC = [[UINavigationController alloc]initWithRootViewController:mainVC];
                        [navigationVC  setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
                        [self dismissViewControllerAnimated:NO completion:^{
                            app.window.rootViewController = navigationVC;
                        }];
                        [self presentViewController:navigationVC animated:YES completion:^{
                            
                        }];
                   
//                        MainViewController *vc = [MainViewController new];
//                        [self.navigationController pushViewController:vc animated:YES];
//
//                        self.navigationController.navigationBar.hidden = NO;
//                        NSArray *vcs = [self.navigationController viewControllers];
//                        for (UIViewController  *childvc in  vcs) {
//                            
//                            if ([childvc isKindOfClass:[LoginViewController class]]) {
//                                
//                                [childvc removeFromParentViewController];
//                                break;
//                            }
//                        }
                        
                    }else{
                        TabBarVC *vc = [TabBarVC new];
                        [self.navigationController pushViewController:vc animated:YES];
                        NSArray *aa = [self.navigationController viewControllers];
                        for (UIViewController *vc in aa) {
                            if ([vc isKindOfClass:[LoginViewController class]]) {
                                [vc removeFromParentViewController];
                                break;
                            }
                        }

                        
                    }
                }
                
            }else if(resuleMod.resltState==ResultFail)
            {
                [MBProgressHUD showError:resuleMod.resultTip];
            }else
            {
                [MBProgressHUD showError:@"网络错误"];
            }
        });
    });

}


#pragma mark 判读是否要跳转绑定手机页面
-(BOOL)isToBingVc
{
    if (self.model.userType == UserTypeTrader) {
        return NO;
    }else if (self.model.mobileType == MobileValidata)
    {
        return NO;
    }
    return YES;
}
/**
 *  保存登陆信息
 */
-(void)saveLoginInfo
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:self.userName.text forKey:@"userName"];
    [defaults setValue:self.pwd.text forKey:@"pwd"];
    [defaults setValue:@"YES" forKey:@"login"];
    
    [defaults synchronize];
    
    
    //获取Documents的全路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //获取文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:@"usermodel"];
    [NSKeyedArchiver archiveRootObject:self.model toFile:path];
    
}

/**
 *  读取保存的登陆信息
 */
-(void)readLoginInfo
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.userName.text = (NSString *)[defaults valueForKey:@"userName"];
}


/**
 *  点击找回密码，到绑定手机页面
 */
- (IBAction)getBackPwd {
    [self.view endEditing:YES];
    
    GetBackPwdViewController *vc = [[GetBackPwdViewController alloc]initWithNibName:@"GetBackPwdViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];

    
}

#pragma mark 点击“申请成为经纪人"
- (IBAction)clickToBeMiddleManBtn
{
    [self.view endEditing:YES];
    [self.navigationController pushViewController:[BrokerRegisterVC new] animated:YES];
}

- (void)keyBoardWillShow:(NSNotification *) notif{
    
    NSDictionary *keyboard = [notif userInfo];
    NSValue *value = [keyboard objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGFloat keyboardHeight = [value CGRectValue].size.height;
    self.keyboardHeight = keyboardHeight;
    
    [UIView beginAnimations:nil context:nil];
    CGRect Viewframe = self.backView.frame;
    
    if (Viewframe.origin.y >= 0) {
        Viewframe.origin.y = - 100;
    }
    self.backView.frame = Viewframe;
    [UIView commitAnimations];
}

- (void)keyBoardWillHide:(id)sender{
    [UIView beginAnimations:nil context:nil];
    CGRect Viewframe = self.backView.frame;
    if (Viewframe.origin.y < 0) {
        Viewframe.origin.y = 0;
    }
    self.backView.frame = Viewframe;
    [UIView commitAnimations];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    [self.userName resignFirstResponder];
    [self.pwd resignFirstResponder];
    return YES;
}

- (IBAction)clickBackView {
        
    [self.view  endEditing:YES];

    
}
@end
